﻿#include "LineEdit_TurnTablePosition.h"

#include <qregexp.h>
#include <qvalidator.h>

LineEdit_TurnTablePosition::LineEdit_TurnTablePosition(QWidget *parent)
  : QLineEdit(parent)
{
  QRegExp regExp("^(-?\\d+)(\\.\\d+)?$");
  setValidator(new QRegExpValidator(regExp, this));
  connect(this, &LineEdit_TurnTablePosition::editingFinished, this, &LineEdit_TurnTablePosition::slot_positionLineEditFinished);
  slot_updatePlaceHolder();
}

LineEdit_TurnTablePosition::~LineEdit_TurnTablePosition()
{
}

float LineEdit_TurnTablePosition::getPosition()
{
  QString value = text();
  if (value.isEmpty())
    {
      return turnTablePositionLowerLimit;
    }
  else
    {
      return value.toFloat();
    }
}
void LineEdit_TurnTablePosition::setPosition(float position)
{
  setText(QString::number(position,'f',accuracy));
  slot_positionLineEditFinished();
}


void LineEdit_TurnTablePosition::slot_positionLineEditFinished()
{
  QString position = text();
  if (position.isEmpty())
    {
      setText(QString::number(turnTablePositionLowerLimit));
      return;
    }
  float position1 = position.toFloat();
  if (position1 > turnTablePositionUpperLimit)
    {
      setText(QString::number(turnTablePositionUpperLimit,'f',accuracy));
    }
  else if (position1 < -turnTablePositionUpperLimit)
    {
      setText(QString::number(-turnTablePositionUpperLimit, 'f', accuracy));
    }
  else if (position1< turnTablePositionLowerLimit && position1>-turnTablePositionLowerLimit)
    {
      if (position1 > 0)
        {
          setText(QString::number(turnTablePositionUpperLimit, 'f', accuracy));
        }
      else if (position1 < 0)
        {
          setText(QString::number(-turnTablePositionUpperLimit, 'f', accuracy));
        }
      else
        {
          setText(QString::number(turnTablePositionLowerLimit, 'f', accuracy));
        }
    }
}
void LineEdit_TurnTablePosition::slot_updatePlaceHolder()
{
  setPlaceholderText(QString::number(-turnTablePositionUpperLimit) + QStringLiteral("至") + QString::number(-turnTablePositionLowerLimit) + QStringLiteral("或") + QString::number(turnTablePositionLowerLimit) + QStringLiteral("至") + QString::number(turnTablePositionUpperLimit));
}


float LineEdit_TurnTablePosition::getTurnTablePositionUpperLimit()
{
  return turnTablePositionUpperLimit;
}
void LineEdit_TurnTablePosition::setTurnTablePositionUpperLimit(float turnTablePositionUpperLimit)
{
  this->turnTablePositionUpperLimit = turnTablePositionUpperLimit;
  slot_updatePlaceHolder();
}
float LineEdit_TurnTablePosition::getTurnTablePositionLowerLimit()
{
  return turnTablePositionLowerLimit;
}
void LineEdit_TurnTablePosition::setTurnTablePositionLowerLimit(float turnTablePositionLowerLimit)
{
  this->turnTablePositionLowerLimit = turnTablePositionLowerLimit;
  slot_updatePlaceHolder();
}
int LineEdit_TurnTablePosition::getAccuracy()
{
  return accuracy;
}
void LineEdit_TurnTablePosition::setAccuracy(int accuracy)
{
  this->accuracy = accuracy;
}
